{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    " \n",
    "def _wgn(x, snr):\n",
    "    \"\"\"\n",
    "    返回对单个信号x来说，满足其指定信噪比snr的高斯白噪声\n",
    "    \n",
    "    参数\n",
    "    -----\n",
    "    x：信号\n",
    "    snr：信噪比\n",
    "    \n",
    "    返回\n",
    "    -----\n",
    "    高斯白噪声\n",
    "    \n",
    "    例子\n",
    "    -----\n",
    "    \n",
    "    >>> noise = _wgn(x, 6)  # 生成x的信噪比为6dB的噪声\n",
    "    >>> xn = x + noise      # 增加了6dBz信噪比噪声的信号\n",
    "    \n",
    "    \"\"\"\n",
    "    snr = 10.0**(snr/10.0)  # -> xpower / npower\n",
    "    xpower = np.sum(x**2)/len(x)\n",
    "    npower = xpower / snr\n",
    "    return np.random.standard_normal(size=x.shape) * np.sqrt(npower)\n",
    "\n",
    "def awgn(X, snr, len_x=2048):\n",
    "    \"\"\"\n",
    "    给指定数据集X增加指定信噪比的噪声\n",
    "    \n",
    "    参数\n",
    "    -----\n",
    "    X:数据集，shape=(M, len_x, 1)或者(M, len_x), M为信号的条数，len_x是信号的长度\n",
    "    snr: 信噪比\n",
    "    \n",
    "    返回\n",
    "    -----\n",
    "    加了指定噪声的数据集X\n",
    "    \"\"\"\n",
    "    X = X.reshape(-1, len_x)\n",
    "    snr = 10.0**(snr/10.0)                #  Xpower / Npower\n",
    "    Xpower = np.sum(X**2，axis=1)/len_x   #  求行向量的平方和，\n",
    "    Xpower = Xpower.reshape(-1,1)         #（len(X),1）, 转成列向量，然后再和X进行对应位置乘法\n",
    "    Npower = Xpower / snr                 \n",
    "    return X + np.multiply(np.sqrt(Npower), np.random.standard_normal(size=X.shape))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
